package viewers;

import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;

import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JProgressBar;

import net.miginfocom.swing.MigLayout;

/**
 * A simple progress indicator
 * @author benjamin
 	This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
public class ProgressIndicator extends JDialog implements Observer {
	private static final int WIDTH = 450;
	private static final int HEIGHT = 350;
	private JProgressBar pgbProgress = new JProgressBar();
	private JLabel lblProgress = new JLabel("Please wait. This may take a while...");
	/**
	 * Sets up the label and progressbar and centers the window
	 */
	public void init(){
		
		setLayout(new MigLayout());
		GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
		Dimension screenSize = new Dimension(gd.getDisplayMode().getWidth(),gd.getDisplayMode().getHeight());
		setBounds(screenSize.width/2-WIDTH/2, screenSize.height/2-HEIGHT/2, WIDTH, HEIGHT);
		add(lblProgress,"wrap, align center");
		int pgbWidth = (int)(7/(float)8*WIDTH);
		add(pgbProgress,"width "+pgbWidth+":"+pgbWidth+":"+pgbWidth);
		pgbProgress.setStringPainted(true);
		setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
		setResizable(false);
		pack();
		setVisible(true);
		toFront();
	}



	/**
	 * (See JDialog)
	 */
	public ProgressIndicator() {
		super();
		init();
	}

	/**
	 * (See JDialog)
	 */
	public ProgressIndicator(Dialog owner, String title, boolean modal) {
		super(owner, title, modal);
		init();
	}


	/**
	 * (See JDialog)
	 */
	public ProgressIndicator(Dialog owner, String title) {
		super(owner, title);
		init();
	}



	/* Event handler for the event-driven MVC pattern
	 * @see viewers.Observer#onObservation(java.lang.String, java.lang.Object)
	 */
	@Override
	public void onObservation(String id, Object value) {
		// TODO Auto-generated method stub
		if (id.equals("PROGRESSUPDATE")){
			final Object v = value;
			javax.swing.SwingUtilities.invokeLater(new Runnable() {
	            public void run() {
	            	int p = (int)Float.parseFloat(v.toString());
	            	pgbProgress.setValue(p);
	            	pgbProgress.setString(String.valueOf(p)+"%");
	            }
			});	
		};
	}

}
